<?php

class nCore {

	private $dirN;
	private $dirApp;
	private $configStatic;
	private $tr_dirs;

	private function __construct($dirApp) {
		$this->dirN     = dirname(__FILE__);
		$this->dirApp   = $dirApp;
		$this->configStatic = include $this->dirConfig() . DIRECTORY_SEPARATOR . 'config.php';
		$this->tr_dirs = array(
			'%DIR_N%'   => $this->dirN,
			'%DIR_APP%' => $this->dirApp
		);
		spl_autoload_register(array($this, 'autoloader'));
		$includeDirs = $this->getConfig('includeDirs');
		if (is_array($includeDirs))
			array_walk($includeDirs, array($this, 'addIncludePath'));
	}

	public function boot() {
		nRouter::i()->route();
	}

	/** @return nCore */
	public static function i($dirApp = 'app') {
		static $instance;
		if (is_object($instance))
			return $instance;
		else
			return $instance = new self($dirApp);
	}

	public function dirN()      { return $this->dirN; }
	public function dirApp()    { return $this->dirApp; }
	public function dirConfig() { return $this->dirApp . DIRECTORY_SEPARATOR . 'config'; }

	public function addIncludePath($path) {
		$path = strtr($path, $this->tr_dirs);
		set_include_path(get_include_path() . PATH_SEPARATOR . $path);
	}

	public function autoloader($name) {
		include_once $name . '.class.php';
	}

	public function getConfig($path, $default = null) {
		if (is_scalar($path))
			$path = split('/', $path);
		$pointer = &$this->configStatic;
		while ($key = array_shift($path)) {
			if (is_array($pointer) && array_key_exists($key, $pointer))
				$pointer = &$pointer[$key];
			else
				return $default;
		}
		return $pointer;
	}

}
